from django.http import JsonResponse
from utils.mixins import StockItemImpWorkUpdateModelMixin as UpdateModelMixin
from utils.mixins import StockItemImpWorkDeleteModelMixin as DestroyModelMixin
from drf_spectacular.utils import extend_schema,inline_serializer
from rest_framework.decorators import action
from rest_framework.mixins import (CreateModelMixin, ListModelMixin,
                                   RetrieveModelMixin)
from rest_framework.viewsets import GenericViewSet
from utils.autoschema import AutoDocSchema, custom_response_serailizer
from utils.decorators import error_response, request_data, check_group_permission
from backend.cews.models import StockItem, StockItemImprovementWork
from .serializers import (StockItemImpWorkSerializer, StockItemImpWithDescriptionWorkSerializer)
from rest_framework import serializers
from rest_framework.response import Response
from django.db import transaction
from backend.cews.models import Log
import json
from backend.cews.services import ImpWorkService


class StockItemImprovementWorkViewSet(
    RetrieveModelMixin,
    ListModelMixin,
    UpdateModelMixin,
    GenericViewSet,
    CreateModelMixin,
    DestroyModelMixin
):
    serializer_class = StockItemImpWorkSerializer
    queryset = StockItemImprovementWork.objects.all()

    @request_data(keys=['stock_code','doc_name','description','completed','invalid','version'],optional=['completed','invalid'])
    @error_response(ValueError,StockItem.DoesNotExist)
    @check_group_permission('add_stockitemimprovementwork')
    def create(self,request,stock_code,doc_name,description,completed=0,invalid=0,version=''):
        stock_item = StockItem.objects.filter(stock_code=stock_code).first()
        
        if not completed:
            completed = 0
        if not invalid:
            invalid = 0
        
        file = request.FILES.get('file',None)

        data = {
            'stock_item':stock_item.id,
            'stock_code':stock_item.stock_code,
            'doc_name':doc_name,
            'description':description,
            'completed':completed,
            'invalid':invalid,
            'file':file,
            'version':version,
        }
        
        ## check is there any duplicated stock item imp work
        dup = StockItemImprovementWork.objects.filter(stock_item=stock_item,doc_name=doc_name)
        to_update = []
        for sie in dup:
            sie.invalid = 1
            to_update.append(sie)

        with transaction.atomic():

            StockItemImprovementWork.objects.bulk_update(to_update,['invalid'])            
            new_log = Log(
                username=request.user.username,
                log_type=Log.LogType.STOCKMASTER,
                category_type=Log.CategoryType.EDOC,
                action_type=Log.ActionType.CREATE,
                action='create_stock_item_improvement_work',
                payload= data,
                description=f"Stock Code:{stock_item.stock_code}, improvement work: {doc_name} is created",
                repair_order=0,
                parent_stock_code='',
                parent_part='',
                part='',
                stock_code=stock_item.stock_code
            )
            new_log.save()

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        return Response(serializer.data, status=201, headers=headers)
        
    
    @extend_schema(responses=custom_response_serailizer(StockItemImpWorkSerializer(many=True)))
    @action(detail=False, methods=['post'], schema=AutoDocSchema())
    @request_data(keys=['stock_code'])
    @error_response()
    def get_stock_item_imp_works(self,request,stock_code):
        sie = ImpWorkService.get_stock_item_imp_work_by_stock_code(stock_code).order_by('id')
        return JsonResponse(data={
            'code':1,
            'data':StockItemImpWithDescriptionWorkSerializer(sie,many=True).data,
        },status=200)
        
        